/**
 * Created by jackliu on 15/12/16.
 */

var common = require('../../common');
var pool = require('../index');
var mysql = require('mysql');
var ItbBaseModel = require('./ItbBaseModel');


// Schema 结构
var TgUserPageModel = function(obj){
    ItbBaseModel.call(this,obj);

  // 以下为表定义数据，需要的字段就填入
  //`page_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '用户文档页ID',
  //`doc_id` bigint(20) unsigned NOT NULL COMMENT '用户文档ID',
  //`design_page_id` bigint(20) unsigned NOT NULL COMMENT '设计模板页ID',
  //`page_index` int(3) NOT NULL DEFAULT '0' COMMENT '页下标（0开始）',
  //`backup_flg` int(1) NOT NULL DEFAULT '0' COMMENT '0普通页; 1保留页',
  //`data` mediumtext COMMENT '模版页内容',
  //`hash_tag` bigint(20) DEFAULT '0' COMMENT '编组对象标记',
  //`thumb` text COMMENT '缩略图',
  //`create_time` datetime NOT NULL,
  //`update_time` datetime NOT NULL,
  //`update_by` varchar(50) NOT NULL DEFAULT '',
  //`del_flg` int(1) NOT NULL DEFAULT '0',

};
TgUserPageModel.prototype = new ItbBaseModel();

// 取得表名
TgUserPageModel.prototype.getTableName = function(){
    return 'tg_user_page';
}
// 取得查询语句中where 后面匹配主键的条件（需要各派生类进行重载）
TgUserPageModel.prototype.getWhereConditionOfKeyEqual = function(){
    return 'page_id='+this.page_id;
}

// 取得排序方法（需要各派生类进行重载）
TgUserPageModel.prototype.getOrderBy = function(){
    return ' page_index asc ';
}

//------------------------------------------------------------------
// 根据doc_id/page_id逻辑删除对应pages
TgUserPageModel.prototype.delPageLogic = function(callback){
    var THIS = this;
    var tableName = this.getTableName();

    pool.pool.getConnection(function(err, connection) {
        // Use the connection
        var sql = 'UPDATE tg_user_page '+
            ' SET del_flg=1, update_time=sysdate(), update_by= '+THIS.update_by+
            ' WHERE del_flg = 0 ';
        var config=false;
        if(typeof THIS.doc_id!='undefined' && THIS.doc_id != null) {
            sql += ' AND doc_id= '+ THIS.doc_id;
            config=true;
        }
        if(typeof THIS.page_id!='undefined' && THIS.page_id != null) {
            sql += ' AND page_id= '+ THIS.page_id;
            config=true;
        }
        if(!config){
            return callback("却少参数");
        }

        //var sqlValue = [THIS.update_by, THIS.doc_id];
        //var sql = mysql.format(sql, sqlValue);
        connection.query(sql, function(error, result) {
            // And done with the connection.
            connection.release();
            console.log(sql);

            if(error) {
                callback(error);
            } else {
                callback(null);
            }
        });
    });
}
//------------------------------------------------------------------


//------------------------------------------------------------------
// 将某个doc的page_index大于指定值的
TgUserPageModel.prototype.updatePageIndex = function(doc_id, page_index, update_by,offset,callback){
    var THIS = this;
    var tableName = this.getTableName();

    pool.pool.getConnection(function(err, connection) {
        // Use the connection
        var sql = 'UPDATE tg_user_page '+
            ' SET page_index=page_index+ '+ offset+', update_time=sysdate(), update_by= '+update_by+
            ' WHERE del_flg = 0 ';

        sql += ' AND doc_id='+ doc_id;
        sql += ' AND page_index>'+ page_index;


        //var sqlValue = [THIS.update_by, THIS.doc_id];
        //var sql = mysql.format(sql, sqlValue);
        connection.query(sql, function(error, result) {
            // And done with the connection.
            connection.release();
            console.log();

            if(error) {
                callback(error);
            } else {
                callback(null);
            }
        });
    });
}
//------------------------------------------------------------------

//------------------------------------------------------------------
// 复制设计模版的page信息 到新的用户文档
TgUserPageModel.prototype.copyPageFromDesign = function(callback, designId){
    var THIS = this;

    pool.pool.getConnection(function(err, connection) {
        // Use the connection
        var sql =
            " INSERT INTO TG_USER_PAGE "+
            " (doc_id, design_page_id, page_index, backup_flg, data, hash_tag, "+
            " thumb, create_time, update_time, update_by, del_flg) "+
            " SELECT " +THIS.doc_id +", page_id, page_index, backup_flg, data, hash_tag, "+
            " null, sysdate(), sysdate(), " +THIS.update_by +", 0 "+
            " FROM TG_DESIGN_PAGE WHERE del_flg=0 AND design_id = " +designId;

        //var sqlValue = [ THIS.docId, THIS.designId ];
        //var sql = mysql.format(sql, sqlValue);
        console.log(sql);
        connection.query(sql, function(error, result) {
            // And done with the connection.
            connection.release();

            if (error)
                console.log(error);

            callback(error);
        });
    });
}
//------------------------------------------------------------------

//------------------------------------------------------------------
// 复制设计模版的page信息 到已存在用户文档
TgUserPageModel.prototype.updPageFromDesign = function(callback, designId){
    var THIS = this;

    pool.pool.getConnection(function(err, connection) {
        // Use the connection
        var sql =
            " UPDATE TG_USER_PAGE t, TG_DESIGN_PAGE d "+
            " SET t.data=d.data, t.hash_tag=d.hash_tag, t.thumb=null "+
            " , t.update_time=sysdate(), t.update_by= "+ THIS.update_by+
            " WHERE t.del_flg=0 AND t.doc_id=" +THIS.doc_id+
            " AND d.del_flg=0 AND d.design_id=" +designId+
            " AND t.design_page_id=d.page_id AND t.page_index=d.page_index ";

        //var sqlValue = [ THIS.docId, THIS.designId ];
        //var sql = mysql.format(sql, sqlValue);
        console.log(sql);
        connection.query(sql, function(error, result) {
            // And done with the connection.
            connection.release();

            if (error)
                console.log(error);

            callback(error);
        });
    });
}
//------------------------------------------------------------------

//------------------------------------------------------------------
/* 根据doc_id/page_id获取page信息
 * 参数:callback:回调
 */
TgUserPageModel.prototype.getPageInfoById = function(callback){
    var THIS = this;
    var tableName = this.getTableName();

    pool.pool.getConnection(function(err, connection) {
        if (err) {
            console.log('TgUserPageModel.getPageInfoById Err:'+err);
        }
        // Use the connection
        var sql = ' SELECT * FROM TG_USER_PAGE t WHERE t.del_flg = 0 ';
        if(THIS.doc_id) {
            sql += ' AND t.doc_id =' + THIS.doc_id;
        }
        if(THIS.page_id){
            sql += ' AND t.page_id =' + THIS.page_id;
        }
        sql+=' ORDER BY t.doc_id, t.page_index ';

        //var sqlValue = [];
        //var sql = mysql.format(sql, sqlValue);
        //console.log(sql);
        connection.query(sql, function(error, result) {
            // And done with the connection.
            connection.release();

            console.log();

            callback(error, result);
        });
    });
}
//------------------------------------------------------------------

//------------------------------------------------------------------
// 根据doc_id/page_id清除预览图
TgUserPageModel.prototype.clrPageThumb = function(callback){
    var THIS = this;
    var tableName = this.getTableName();

    pool.pool.getConnection(function(err, connection) {
        // Use the connection
        var sql = 'UPDATE tg_user_page '+
            ' SET thumb=NULL, update_time=sysdate(), update_by= '+THIS.update_by+
            ' WHERE del_flg = 0 ';
        if(typeof THIS.doc_id!='undefined' && THIS.doc_id != null) {
            sql += ' AND doc_id= '+ THIS.doc_id;
        }
        if(typeof THIS.page_id!='undefined' && THIS.page_id != null) {
            sql += ' AND page_id= '+ THIS.page_id;
        }

        //var sqlValue = [THIS.update_by, THIS.doc_id];
        //var sql = mysql.format(sql, sqlValue);
        connection.query(sql, function(error, result) {
            // And done with the connection.
            connection.release();
            console.log();

            if(error) {
                callback(error);
            } else {
                callback(null);
            }
        });
    });
}
//------------------------------------------------------------------

// 导出
module.exports = TgUserPageModel;